<template>
  <el-dialog :title="title" :width="width" :append-to-body="true" :visible.sync="showDialog" @close="hiddenView">
    <el-upload
      v-show="showFileUpload"
      ref="upload"
      class="upload-demo"
      style="margin-left:20px"
      :auto-upload="false"
      :on-change="uploadFile4Drag"
      accept="image/png, image/jpeg, image/gif, image/jpg"
      drag
      action="https://jsonplaceholder.typicode.com/posts/"
      multiple
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <div v-show="!showFileUpload" v-loading="loading" class="content">
      <div :style="cropperBoxClass">
        <vueCropper ref="cropper" :can-move="true" :auto-crop="true" :fixed="true" :fixed-number="fixedNumber" :img="cropperImg" output-type="png" @realTime="realTime">
        </vueCropper>
      </div>
      <div class="preview">
        <div class="preview-name">预览</div>
        <img :style="{'width': previewWidth, 'height': previewHeight, 'border-radius': previewRadius}" :src="previewImg" class="preview-img">
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="showProgress == false" type="primary" @click="submiteImage()">{{ saveButtonTitle }}</el-button>
      <el-progress v-show="showProgress" :percentage="upProgress" style="margin-top:10px"></el-progress>
      <input :id="upFileId" type="file" style="display:none" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadFile">
    </div>
  </el-dialog>
</template>

<script type="text/javascript">
import * as api from '@/api'
import { VueCropper } from 'vue-cropper'

export default {
  name: 'EditImage', // 处理头像
  components: {
    VueCropper
  },
  props: {
    // 弹窗宽度
    width: {
      type: String,
      default: '500px'
    },
    // 截图区域宽
    cWidth: {
      type: String,
      default: '300px'
    },
    // 截图区域高
    cHeight: {
      type: String,
      default: '300px'
    },
    title: {
      type: String,
      default: '编辑头像'
    },
    saveButtonTitle: {
      type: String,
      default: '开始上传'
    },
    fixedNumber: {
      type: Array,
      default: () => {
        return [1, 1]
      }
    },
    previewWidth: {
      type: String,
      default: '70px'
    },
    previewHeight: {
      type: String,
      default: '70px'
    },
    previewRadius: {
      type: String,
      default: '35px'
    },
    upFileId: {
      type: String,
      default: 'uploadFile'
    },
    upFileUrl: {
      type: String,
      default: '/Api/File/uploadSaveLocal'
    },
    useDrag: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      showDialog: false,
      cropperImg: '',
      previewImg: '',
      file: {},
      image: '',
      show: false,
      upProgress: 0,
      showProgress: false,
      showFileUpload: false,
      cropperBoxClass: {
        width: this.cWidth,
        height: this.cHeight,
        'margin-right': '15px'
      }
    }
  },
  computed: {},
  watch: {
    show: {
      handler(val) {
        this.showDialog = val
      },
      deep: true,
      immediate: true
    },
    image: function(val) {
      this.cropperImg = val
    }
  },
  mounted() {
    this.cropperImg = this.image
  },
  methods: {
    // 显示选择文件弹窗
    selectFile() {
      this.upProgress = 0
      if (this.useDrag) {
        this.showFileUpload = true
        this.show = true
      } else {
        this.showFileUpload = false
        document.getElementById(this.upFileId).click()
      }
    },
    // 图片选择触发
    uploadFile(event) {
      var files = event.target.files
      const file = files[0]
      const reader = new FileReader()
      var self = this
      reader.onload = function(e) {
        let result
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          result = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          result = e.target.result
        }
        self.image = result
        self.file = file
        self.show = true
        event.target.value = ''
      }
      reader.readAsDataURL(file)
    },
    uploadFile4Drag(upFile, fileList) {
      const isLt5M = upFile.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
        return false
      }
      var file = upFile.raw
      const reader = new FileReader()
      var self = this
      reader.onload = function(e) {
        let result
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          result = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          result = e.target.result
        }
        self.image = result
        self.file = file
        self.show = true
        self.showFileUpload = false
        setTimeout(() => {
          self.$refs.upload.clearFiles()
        }, 100)
        // event.target.value = ''
      }
      reader.readAsDataURL(file)
    },
    realTime(data) {
      this.$refs.cropper.getCropData(cropperData => {
        this.previewImg = cropperData
      })
    },
    submiteImage() {
      // 获取截图的blob数据
      this.$refs.cropper.getCropBlob(async data => {
        var formData = new FormData()
        formData.append('file1', data, this.file.name)
        this.showProgress = true

        var res = await api.apiRequest('/Api/File/uploadSaveLocal', null, 'POST', this, 'loading', 3, null, formData, (a, b) => {
          this.upProgress = parseInt((a / b) * 100)
          // console.log(a / b)
        })

        this.$emit('finish', res)

        setTimeout(() => {
          this.showProgress = false
          this.hiddenView()
        }, 1000)
      })
    },
    hiddenView() {
      this.show = false
    }
  }
}
</script>
<style lang="scss" scoped>
.cropper-box {
  width: 300px;
  height: 300px;
  margin-right: 15px;
}

.preview {
  position: absolute;
  bottom: 0;
  right: 0;
  .preview-name {
    margin-bottom: 8px;
    font-size: 13px;
    color: #666;
  }
  .preview-img {
    display: block;
  }
}

.content {
  position: relative;
  padding: 0 30px;
}
</style>
